package com.zhu.classfile.attribute;

import com.zhu.classfile.attribute.factory.AttributeInfoFactory;
import com.zhu.classfile.constant.ConstantPool;

import java.nio.ByteBuffer;

public class CodeAttribute implements AttributeInfo {
    private ConstantPool cp;
    private  int maxStack;
    private  int maxLocals;
    private  byte[] code;
    private  ExceptionTableEntry[] exceptionTable;
    private  AttributeInfo[] attributes;

    public CodeAttribute(ConstantPool cp){
        this.cp=cp;
    }
    @Override
    public void readInfo(ByteBuffer reader) {
         maxStack = Short.toUnsignedInt(reader.getShort());
         maxLocals = Short.toUnsignedInt(reader.getShort());
         int codeLength = reader.getInt();
         code = new byte[codeLength];
         reader.get(code);
         int exceptionTableLength = Short.toUnsignedInt(reader.getShort());
         exceptionTable = new ExceptionTableEntry[exceptionTableLength];
        for (int i = 0; i < exceptionTableLength; i++) {
            int startPc = Short.toUnsignedInt(reader.getShort());
            int endPc = Short.toUnsignedInt(reader.getShort());
            int handlerPc = Short.toUnsignedInt(reader.getShort());
            int catchType = Short.toUnsignedInt(reader.getShort());
            exceptionTable[i] = new ExceptionTableEntry(startPc, endPc, handlerPc, catchType);
        }
        int attributesCount = Short.toUnsignedInt(reader.getShort());
        attributes = AttributeInfoFactory.readAttributes(reader,cp,attributesCount);
    }

    // ------------------------
    // Getter 方法
    // ------------------------

    public int getMaxStack() { return maxStack; }
    public int getMaxLocals() { return maxLocals; }
    public byte[] getCode() { return code; }
    public ExceptionTableEntry[] getExceptionTable() { return exceptionTable; }
    public AttributeInfo[] getAttributes() { return attributes; }

}
